package com.dragonfly.shutter.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.dragonfly.shutter.DAOs.CollectionDAO;
import com.dragonfly.shutter.beans.Message;
import com.dragonfly.shutter.beans.PictureDetail;
import com.dragonfly.shutter.services.PictureService;
import com.dragonfly.shutter.utils.KeywordFilter;

/**
 * 图片显示控制器
 * @author 黄挺
 *
 */
@Controller
@RequestMapping("/picture.html")
public class PictureController {
	@Autowired
	private PictureService pictureService;
	@Autowired
	private CollectionDAO collectionDAO; 
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView OnLoad(@RequestParam(value="pictureID", required = false) String pictureID,
			HttpSession session, HttpServletRequest request, ModelMap model){
		Message message = null; //错误消息
		
		//不存在的图片
		if( pictureID == null ) {
			message = new Message("您访问的图片不存在", "不存在的图片", "/Dragonfly/");
			return new ModelAndView("message", "message", message);
		} 
		
		//参数安全验证
		if(!KeywordFilter.isNumeric(pictureID)){
			message = new Message("非法的参数", "操作失败", "/Dragonfly");
			return new ModelAndView("message", "message", message);
		}
		
		
		
		Integer userID = (Integer)session.getAttribute("userID");
		PictureDetail picture = new PictureDetail();
			
		if( userID != null )
			picture.getPicOwner().setUserID(userID);
		
		try {
			picture = pictureService.doService(pictureID, userID, request.getRequestURL().toString());
		} catch (Exception e) {
			//用户访问权限不够
			message = new Message(e.getMessage(), "权限错误", "/Dragonfly");
			return new ModelAndView("message", "message", message);
		}
		
		//验证图片是否在我的收藏里
		Integer collectionID = collectionDAO.selectOnePic(userID, pictureID);
		
		if(collectionID == null )
			model.addAttribute("isInCollection", false);
		else
			model.addAttribute("isInCollection", true);
		
		return new ModelAndView("picture", "picture", picture);
	}
}
